package com.howells.time.base.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2016.4.4.
 */
public class ViewHolder extends RecyclerView.ViewHolder {
    private final SparseArray<View> mViews;
    private View mConvertView;
    private Context mContext;
    private int mPosition;
    private int mLayoutId;

    public ViewHolder(Context context,View itemView,ViewGroup parent,int position) {
        super(itemView);
        this.mViews = new SparseArray<>();
        mConvertView= itemView;
        mConvertView.setTag(this);
        mPosition=position;
        mContext=context;
    }

    public static ViewHolder get(Context context,View convertview,ViewGroup parent,int layoutId,int position) {
        if (convertview == null) {
            View itemView = LayoutInflater.from(context).inflate(layoutId, parent, false);
            ViewHolder holder = new ViewHolder(context, itemView, parent, position);
            holder.mLayoutId = layoutId;
            return holder;
        } else {
            ViewHolder holder= (ViewHolder) convertview.getTag();
            holder.mPosition=position;
            return holder;
        }
    }

    public <T extends View> T getView(int viewId){
        View view=mViews.get(viewId);
        if(view==null){
            view=mConvertView.findViewById(viewId);
            mViews.put(viewId,view);
        }
        return (T) view;
    }

    public void updatePosition(int position){
        mPosition=position;
    }

    public View getConvertView(){
        return mConvertView;
    }

    public int getLayoutId(){
        return mLayoutId;
    }

    public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener){
        View view=getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public ViewHolder setOnTouchListener(int viewId, View.OnTouchListener listener)
    {
        View view = getView(viewId);
        view.setOnTouchListener(listener);
        return this;
    }

    public ViewHolder setOnLongClickListener(int viewId, View.OnLongClickListener listener)
    {
        View view = getView(viewId);
        view.setOnLongClickListener(listener);
        return this;
    }
}
